<template>
  <div id="progress-loop" ref="chartDom" style="width: 100%; height: 100%;"></div>
</template>

<script setup lang="ts" name="dataScreen">
import { ref, onMounted, onBeforeUnmount, nextTick, watch } from 'vue';
import { debounce } from "@/utils";
import * as echarts from 'echarts';

const props = defineProps({
  echartsRingData: {
    type: Object,
    default: () => ({
      title: '',
      data: []
    }),
  },
});

const chartDom = ref();
let myChart = null;

const initChart = () => {
  if (myChart) {

    const onlineCount = props.echartsRingData.data.find(item => item.name === "在线")?.value || 0; // 如果在线项不存在，返回 0
    const option = {
      title: {
        show: true,
        text: props.echartsRingData.title || 'No Title',
        textStyle: {
          fontSize: 12, // 根据设计调整
          color: "#fff",
        },
        left: "left",
        top: "0",
      },
      tooltip: {
        trigger: 'item',
        formatter: "{b} : {c} ({d}%)"
      },
      legend: {
        show: true,
        left: 'center',
        top: 'bottom',
        itemWidth: 8,
        itemHeight: 8,
        textStyle: {
          fontSize: 10,
          color: '#fff',
        },
      },
      series: [
        {
          type: 'pie',
          radius: ['40%', '55%'],
          label: {
            show: false,
            position: 'center'
          },
          labelLine: {
            show: false
          },
          data: props.echartsRingData.data || [],

        }
      ],
      graphic: [
        {
          type: 'text',
          left: '50%',
          top: '50%',
          style: {
            text: onlineCount, // 在线数量
            textAlign: 'center',
            fill: '#fff', // 文字颜色
            fontSize: 20,
            fontWeight: 'bold',
          },
          z: 100, // 确保文本在最上层
          bounding: 'raw' // 确保文本不被裁剪
        }
      ],
    };
    myChart.setOption(option);
  }
};

// 处理图表缩放
const handleChartResize = debounce(() => {
  if (myChart) {
    myChart.resize();
  }
}, 100);

// 组件挂载时
onMounted(() => {
  nextTick(() => {
    myChart = echarts.init(chartDom.value);
    initChart();
  });

  window.addEventListener("resize", handleChartResize);
});

// 监视数据变化
watch(() => props.echartsRingData, () => {
  initChart();
}, { deep: true });

// 组件卸载时清理
onBeforeUnmount(() => {
  window.removeEventListener("resize", handleChartResize);
  if (myChart) {
    myChart.dispose();
  }
});
</script>
